const router = require("express").Router();
const userController = require("../controllers/userController");

/**
 * Express 是通过 next(error) 来表达出错的，无法识别 async 函数抛出的错误
 * wrap 函数的作用在于将 async 函数抛出的错误转换为 next(error)
 * @param {function} handler 处理req,res的控制器
 * @returns {function} 处理req,res的中间件
 */
function wrap(handler) {
  return async (req, res, next) => {
    try {
      await handler(req, res, next);
    } catch (err) {
      next(err);
    }
  };
}

//组装路由,遵循rest风格
router.get("/all", wrap(userController.getAllUsers));
router.get("/:id", wrap(userController.findUser));
router.put("/:id", wrap(userController.update));
router.delete("/:id", wrap(userController.delete));
router.post("/", wrap(userController.create));
router.post("/avatar", wrap(userController.uploadAvatar));
router.get("/avatar/:id", wrap(userController.downloadAvatar));

//导出路由
module.exports = router;
